<template>
  <div class="box">
    <el-empty style="width: 100%;" description="暂无数据" v-if="data.tableData.length === 0" />
    <div style="flex:1">
        <el-card class="list-box" shadow="hover" style="margin-bottom: 10px" v-for="(item,i) in data.tableData" :key="item.id">
            <img style="width:500px;height: 200px;margin-right: 20px;"  :src="imgList[i%5]" alt=""/>
            <div class="box-card list-item">
              <div>
                <h4>具体赛事：{{ item.eventName }}</h4>
                <div>赛事文件名称：{{ item.fileName}}</div>
              </div>

                <el-button @click="downloadFn(item)" type="primary" style="width: 80px;">下载</el-button>
            </div>
          

        </el-card>
    </div>
</div>

</template>

<script setup>
import {reactive,ref} from "vue";
import {Delete, Edit, Search ,Download} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import img1 from '@/assets/01.jpeg'
  import img2 from '@/assets/02.jpeg'
  import img3 from '@/assets/03.jpeg'
  import img4 from '@/assets/04.jpeg'
  import img5 from '@/assets/05.jpeg'
const imgList = [img1,img2,img3,img4,img5]
const fileList = ref([])
const beforeUpload = (file) => {
                    const isJpgOrPng = ['image/jpeg', 'image/png'].includes(file.type);
                    if (!isJpgOrPng) {
                        ElementPlus.ElMessage.error('仅支持上传 jpg、png 文件');
                        return false;
                    }
                    const isLt2M = file.size / 1024 / 1024 < 2;
                    if (!isLt2M) {
                        ElementPlus.ElMessage.error('单个文件大小不能超过 2MB');
                        return false;
                    }
                    return true
                };

const httpRequest = (file) => {
  fileList.value.push(file)
    console.log(fileList.value)
}

// 下载
const downloadFn = (row) => {
  const link = document.createElement('a') // 创建a标签
      link.download = row.fileName // 由于下方的下载链接会跨域，所以此处的download属性失效，文件名并不会修改，如有需求，可以使用new XMLHttpRequest()解决
      link.style.display = 'none'
      link.href = `http://localhost:9090/file/download/${row.id}`
      document.body.appendChild(link)
      link.click() // 执行下载
      document.body.removeChild(link) // 释放标签
    }
const closeFn = () => {
  data.FormVisible = false
  fileList.value = []
  data.form = {
    fileName: '',
    eventId:''
  }
}
const data = reactive({
  eventName: '',
  fileName: '',
  description: '',
  form: {
    fileName: '',
    eventId:''
  },
  tableData: [],
  currentPage: 1,
  pageSize: 5,
  total: 0,
  FormVisible: false,
  ids: [],
})

const loadByName =()=> {
  // 点击查询时重置到第一页
  data.currentPage = 1

  request.get('/file/selectPage', {
    params: {
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      role: 'PARTICIPANT',
      eventName: data.eventName.trim(), // 传递查询参数
    }
  }).then(res => {
    data.tableData = res.data.list
    data.total = res.data.total
  })
}

const load = () => {
  request.get('/file/selectPage', {
    params: {
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      eventName: data.eventName.trim(),
      //role: 'PARTICIPANT' // 只查询参赛者
    }
  }).then(res => {
    data.tableData = res.data.list;
    data.total = res.data.total;
  })

}

load()

const reset = () => {
  data.eventName = '';
  load()
}

//新增
const hadleNewracer = () => {
  data.FormVisible = true;
  data.form = {};//新增时清空表单，防止上一次数据残留
}

// 新增 和 保存信息
const save = () => {
  data.form.id ? update() : add()//id有值跟新，无添加
}

const add = () => {
console.log(fileList.value[0].file)
  const formData = new FormData()

  // 添加其他参数
  formData.append('file',fileList.value[0].file)
  formData.append('eventId',data.form.eventId)
  request.post("/file/upload", formData, {
      headers: {
        'Content-Type': 'multipart/form-data'  // 必须设置
      }}

  ).then(res => {
    if (res.code === '200') {
      ElMessage.success("操作成功")
      closeFn()
      load()

    } else {
      ElMessage.error(res.msg)
    }

  })
}
const selectList = ref([])
const getList = () => {
  request.get('/evertInformation/SelectPage', {
      params: {
        pageNum: 1,
        pageSize: 999,
      }
    }).then(res => {
      selectList.value = res.data?.list || [];
    });
}
getList()
const update = () => {
  const formData = new FormData();

  formData.append('file',fileList.value[0].file)
  formData.append('eventId',data.form.eventId)
  formData.append('id',data.form.id)
  request.put("/file", formData,{
            "Content-Type": "multipart/form-data; charset=UTF-8",
        }).then(res => {
    if (res.code === '200') {
      ElMessage.success("操作成功")
      closeFn()
      load()
    } else {
      ElMessage.error(res.msg)
    }

  })
}


// 数据编辑
const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row))//深拷贝，不直接data.from=row,此时会直接修改
  data.FormVisible = true
}

// 数据删除
const handleDelete = (id) => {///eventCategory/delEventCategory
  ElMessageBox.confirm('您确认删除', '删除确认', {type: "warning"}).then(() => {
    request.delete("/file/" + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        data.FormVisible = false; //删除后 关闭对话框
        load()
      } else {
        ElMessage.error(res.msg)
      }

    })
  }).catch()

}

const handleSelectionChange = (rows) => {//返回所有选中的行对象数组

  //从选中行数组里的里面取出所有行的id组成一个新的数组
  data.ids = rows.map(row => row.id)
  console.log(data.ids)
}

const deleteBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('您确认删除', '删除确认', {type: "warning"}).then(() => {///eventCategory/delEventCategoryBaTch
    request.delete('/file/batch', {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        data.FormVisible = false; //删除后 关闭对话框
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()

}

</script>

<style scoped>
  ::v-deep .el-card__body{
    display: flex !important;
  }
  .box-card{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
</style>
